<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑角色' : '新增角色'"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      label-position="right"
    >
      <el-form-item label="角色代码" prop="code">
        <el-input 
          v-model="form.code" 
          placeholder="请输入角色代码" 
          :disabled="isEdit"
        />
        <div class="form-tip">
          <el-text type="info" size="small">
            角色代码用于系统内部识别，创建后不可修改
          </el-text>
        </div>
      </el-form-item>

      <el-form-item label="角色名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入角色名称" />
      </el-form-item>

      <el-form-item label="角色描述" prop="description">
        <el-input 
          v-model="form.description" 
          type="textarea" 
          :rows="3" 
          placeholder="请输入角色描述" 
        />
      </el-form-item>

      <el-form-item label="启用状态" prop="enable">
        <el-switch 
          v-model="form.enable" 
          active-text="启用" 
          inactive-text="禁用" 
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import { 
  userApi, 
  CreateRoleData, 
  UpdateRoleData, 
  Role
} from '../api/user'

// Props
interface Props {
  modelValue: boolean
  role?: Role | null
  isEdit: boolean
}

const props = withDefaults(defineProps<Props>(), {
  role: null,
  isEdit: false
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

// 表单引用
const formRef = ref<InstanceType<typeof ElForm> | null>(null)

// 提交状态
const submitting = ref(false)

// 对话框显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 表单数据
const form = reactive<CreateRoleData>({
  code: '',
  name: '',
  description: '',
  enable: true
})

// 表单验证规则
const rules = {
  code: [
    { required: true, message: '请输入角色代码', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
    { pattern: /^[A-Z_][A-Z0-9_]*$/, message: '角色代码只能包含大写字母、数字和下划线，且必须以字母或下划线开头', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    code: '',
    name: '',
    description: '',
    enable: true
  })
  
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 填充表单数据
const fillForm = (role: Role) => {
  Object.assign(form, {
    code: role.code,
    name: role.name,
    description: role.description || '',
    enable: role.enable !== false
  })
}

// 监听对话框显示状态
watch(() => props.modelValue, (visible) => {
  if (visible) {
    if (props.isEdit && props.role) {
      fillForm(props.role)
    } else {
      resetForm()
    }
  }
})

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true
      try {
        if (props.isEdit && props.role) {
          // 更新角色
          const updateData: UpdateRoleData = { ...form }
          // 编辑时不需要传递code字段
          delete (updateData as any).code
          const res = await userApi.updateRole(props.role.id, updateData)
          
          if (res && res.code === 200) {
            ElMessage.success('更新角色成功')
            emit('success')
          } else {
            ElMessage.error('更新角色失败')
          }
        } else {
          // 创建角色
          const createData: CreateRoleData = { ...form }
          const res = await userApi.createRole(createData)
          
          if (res && res.code === 200) {
            ElMessage.success('创建角色成功')
            emit('success')
          } else {
            ElMessage.error('创建角色失败')
          }
        }
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败，请重试')
      } finally {
        submitting.value = false
      }
    }
  })
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.form-tip {
  margin-top: 4px;
}
</style>
